from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.core.paginator import Paginator
from django.core.mail import send_mail

from datetime import datetime
from .models import Student
from .models import Gitinfo
from info import settings
import os
import time

# Create your views here.
# todo  定时 邮件

def index(request):
    return render(request, 'index.html')


def testpost(request):
    if request.method == "GET":
        return render(request, 'testpost.html')
    if request.method == "POST":
        wd = request.POST.get("wd", "")
        print(wd)
        return HttpResponse('ok')





def info(request):
    if request.method == "GET":
        clses = Tclass.objects.all()
        return render(request, 'info.html',{"clses":clses})
    if request.method == "POST":
        name = request.POST.get("name", "")
        gitaddr = request.POST.get("gitaddr", "")
        cls = request.POST.get("cls", "")

        # gitinfo = Gitinfo(name=name,
        #                   gitaddr=gitaddr,
        #                   classblong_id=1
        #                   )
        gitinfo = Gitinfo(name=name,
                          gitaddr=gitaddr,
                          classblong_id=cls
                          )
        gitinfo.save()
        return HttpResponse("ok")




def genpicname(filename):
    """
    根据一个名称  xx.jpg 生成一个唯一的新的文件名
    :param filename:
    :return:
    """
    prefix, suffix = filename.rsplit('.', maxsplit=1)

    bfilename = (prefix + str(time.time())).encode('utf-8')

    return md5(bfilename).hexdigest() + "." + suffix


def saveicon(iconfile):
    """
    根据iconfile保存文件到 static/img 路径下
    根据iconfile保存文件到 static/img/teacher路径下,以后专门保存老师图片信息
    :param iconfile:
    :return: 文件的名称
    """
    save_path = os.path.join(settings.BASE_DIR, 'static', 'img', 'teacher')
    # filename = iconfile.name.split('.')[0] + str(time.time()).split('.')[0] + "." + iconfile.name.split('.')[1]
    filename = genpicname(iconfile.name)
    with open(os.path.join(save_path, filename), 'wb') as f:
        for chunk in iconfile.chunks():
            f.write(chunk)

    return filename


def save_studentpic(iconfile):
    """
    根据iconfile保存文件到 static/img/student 路径下
    :param iconfile:
    :return: 文件的名称
    """
    save_path = os.path.join(settings.BASE_DIR, 'static', 'img', 'student')
    # filename = iconfile.name.split('.')[0] + str(time.time()).split('.')[0] + "." + iconfile.name.split('.')[1]
    filename = genpicname(iconfile.name)
    with open(os.path.join(save_path, filename), 'wb') as f:
        for chunk in iconfile.chunks():
            f.write(chunk)

    return filename


from hashlib import md5

from .models import Teacher


def teacher(request):
    if request.method == "GET":
        return render(request, 'teacher.html')
    if request.method == "POST":
        name = request.POST.get("name", "")
        jobtype = request.POST.get("jobtype", "")
        salary = request.POST.get("salary", "")
        phone = request.POST.get("phone", "")
        icon_file = request.FILES.get("icon", "")

        icon_name = saveicon(icon_file)

        introduction = request.POST.get("introduction", "")

        t1 = Teacher(
            name=name,
            jobtype=jobtype,
            salary=salary,
            phone=phone,
            icon=icon_name,
            introduction=introduction
        )

        # 获取icon 保存icon 存储路径
        t1.save()

        return HttpResponse('teacher')


def showteacher(request, teacherid):
    t1 = Teacher.objects.get(pk=teacherid)

    return render(request, 'showteacher.html', {"teacher": t1})


from .models import Tclass


def cls(request):
    if request.method == "GET":
        # 导员和讲师 有哪些
        # 先将老师的信息查询出来 传递给前端

        # 将讲师查询出来
        lecturers = Teacher.objects.filter(jobtype='0').all()
        # 将导员查询出来
        instructors = Teacher.objects.filter(jobtype='1').all()

        return render(request, 'cls.html', {"lecturers": lecturers, "instructors": instructors})
    if request.method == "POST":
        clsname = request.POST.get("clsname", "")
        stucount = request.POST.get("stucount", "")
        stucount = int(stucount.strip())

        # 传递id  注意!!!
        lecturer = request.POST.get("lecturer", "")
        instructor = request.POST.get("instructor", "")

        classno = request.POST.get("classno", "")
        subject = request.POST.get("subject", "")

        tcls = Tclass(
            clsname=clsname,
            stucount=stucount,
            lecturer_id=lecturer,
            instructor_id=instructor,
            classno=classno,
            subject=subject,
        )
        tcls.save()
        return HttpResponse('班级录入成功!')


def teachers(request):
    """
    展示所有老师信息
    :param request:
    :return:
    """
    ts = Teacher.objects.all()

    return render(request, 'teachers.html', {"teachers": ts})


def clses(request):
    """
    展示所有班级的信息
    :param requests:
    :return:
    """
    clses = Tclass.objects.all()

    return render(request, 'clses.html', {"clses": clses})




def student(request):
    """
    添加学生
    :param request:
    :return:
    """
    if request.method == "GET":
        tclses = Tclass.objects.all()
        return render(request, 'student.html', {'tclses': tclses})

    if request.method == "POST":
        stu_name = request.POST.get("stu_name", '')
        sex = request.POST.get("sex", '0')
        cls = request.POST.get("cls", '')

        # 图片另说 todo
        file = request.FILES.get("img_path", '')

        img_path = save_studentpic(file)

        ymd = request.POST.get("ymd", '')
        # 2021-11-04T14:04 datetime-local
        # 2021-11-11  date
        # 15:07  time

        fmt = "%Y-%m-%d"
        birthday = datetime.strptime(ymd, fmt)
        birthyear = birthday.year  # 通过date获取到年

        s1 = Student(
            stu_name=stu_name,
            sex=sex,
            cls_id=cls,
            img_path=img_path,
            birthday=birthday,
            birthyear=birthyear,
        )
        s1.save()
        return HttpResponse("提交学生信息成功")





def students(request):
    """
    展示所有学生信息
    :param request:
    :return:
    """
    students = Student.objects.all()

    per_page = 5
    paginator = Paginator(students, per_page)
    num = request.GET.get('page', '1')

    try:
        num = int(num)
    except Exception as e:
        mun = 1

    pagex = paginator.get_page(num)
    studentx = pagex.object_list

    return render(request, 'students.html', {"studentx": studentx})
